package com.lanzuo.yxd.scanner.conveyor;

import com.ghgande.j2mod.modbus.facade.ModbusTCPMaster;
import com.ghgande.j2mod.modbus.procimg.InputRegister;
import com.ghgande.j2mod.modbus.procimg.Register;
import com.ghgande.j2mod.modbus.procimg.SimpleInputRegister;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ModbusMaster {
    static final Integer UNIT_ID = 1;
    private String ip;
    private Integer port;

    public ModbusMaster(String ip, Integer port) {
        this.ip = ip;
        this.port = port;
    }

    /**
     * 寄存器写数据
     *
     * @param address 寄存器地址
     * @param value   新值
     * @return 写入的值返回，异常则返回null
     */
    public Integer writeSignal(Integer address, Integer value) {
        ModbusTCPMaster master = null;
        try {
            // 创建 TCP Master，连接到从站 Modbus.DEFAULT_PORT 默认端口 502
            master = new ModbusTCPMaster(ip, port);
            master.connect();

            Register register = new SimpleInputRegister();
            register.setValue(value);
            return master.writeSingleRegister(UNIT_ID, address, register);
        } catch (Exception e) {
            log.error("写入plc失败，无法连接", e);
        } finally {
            if (master != null) {
                master.disconnect();
            }
        }

        return null;
    }

    /**
     * 寄存器读值
     *
     * @param address 寄存器地址
     * @return value or null(读取异常)
     */
    public Integer readSignal(Integer address) {
        ModbusTCPMaster master = null;
        try {
            // 创建 TCP Master，连接到从站 Modbus.DEFAULT_PORT 默认端口 502
            master = new ModbusTCPMaster(ip, port);
            master.connect();

            InputRegister[] registers = master.readMultipleRegisters(UNIT_ID, address, 1);

            if (registers.length > 0) {
                return registers[0].getValue();
            }

        } catch (Exception e) {
            log.error("传感器信号未开启，无法连接", e);
        } finally {
            if (master != null) {
                master.disconnect();
            }
        }

        return null;
    }
}
